package com.inventory.controller;

import com.inventory.model.Product;
import com.inventory.model.SaleRecord;
import com.inventory.model.User;
import com.inventory.service.ProductService;
import com.inventory.service.SaleRecordService;
import com.inventory.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Controller
@RequestMapping("/sales")
public class SaleController {

    @Autowired
    private SaleRecordService saleRecordService;
    
    @Autowired
    private ProductService productService;
    
    @Autowired
    private UserService userService;

    @GetMapping
    public String listSales(Model model,
                           @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
                           @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
        
        LocalDateTime start = startDate != null ? startDate.atStartOfDay() : LocalDateTime.now().minusMonths(1);
        LocalDateTime end = endDate != null ? endDate.atTime(LocalTime.MAX) : LocalDateTime.now();
        
        model.addAttribute("sales", saleRecordService.findByDateRange(start, end));
        model.addAttribute("startDate", startDate);
        model.addAttribute("endDate", endDate);
        model.addAttribute("totalAmount", saleRecordService.getTotalSaleAmount(start, end));
        model.addAttribute("totalProfit", saleRecordService.getTotalProfit(start, end));
        
        return "sale/list";
    }
    
    @GetMapping("/add")
    public String showAddForm(Model model, @RequestParam(required = false) Long productId) {
        SaleRecord saleRecord = new SaleRecord();
        
        // 如果指定了商品ID，则预先设置商品
        if (productId != null) {
            Optional<Product> productOpt = productService.findById(productId);
            if (productOpt.isPresent()) {
                Product product = productOpt.get();
                saleRecord.setProduct(product);
                saleRecord.setPrice(product.getSellingPrice()); // 设置默认售价
            }
        }
        
        model.addAttribute("saleRecord", saleRecord);
        model.addAttribute("products", productService.findActiveProducts());
        return "sale/form";
    }
    
    @PostMapping("/add")
    public String addSale(@ModelAttribute SaleRecord saleRecord,
                         @RequestParam Long productId,
                         Authentication authentication,
                         RedirectAttributes redirectAttributes) {
        try {
            // 获取当前用户
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            Optional<User> userOpt = userService.findByUsername(userDetails.getUsername());
            
            if (!userOpt.isPresent()) {
                redirectAttributes.addFlashAttribute("error", "用户不存在");
                return "redirect:/sales/add";
            }
            
            // 获取商品
            Optional<Product> productOpt = productService.findById(productId);
            
            if (!productOpt.isPresent()) {
                redirectAttributes.addFlashAttribute("error", "商品不存在");
                return "redirect:/sales/add";
            }
            
            Product product = productOpt.get();
            
            // 检查库存是否足够
            if (product.getQuantity() < saleRecord.getQuantity()) {
                redirectAttributes.addFlashAttribute("error", "库存不足，当前库存: " + product.getQuantity() + ", 销售数量: " + saleRecord.getQuantity());
                return "redirect:/sales/add?productId=" + productId;
            }
            
            // 设置销售记录的用户和商品
            saleRecord.setUser(userOpt.get());
            saleRecord.setProduct(product);
            
            // 计算利润
            if (saleRecord.getProfit() == null) {
                saleRecord.prePersist(); // 利用模型中的方法计算利润
            }
            
            // 保存销售记录（同时会更新库存）
            saleRecordService.saveSaleRecord(saleRecord);
            
            redirectAttributes.addFlashAttribute("success", "销售记录添加成功");
            return "redirect:/sales";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "销售记录添加失败: " + e.getMessage());
            return "redirect:/sales/add";
        }
    }
    
    @GetMapping("/detail/{id}")
    public String viewSaleDetail(@PathVariable Long id, Model model, RedirectAttributes redirectAttributes) {
        Optional<SaleRecord> saleOpt = saleRecordService.findById(id);
        
        if (!saleOpt.isPresent()) {
            redirectAttributes.addFlashAttribute("error", "销售记录不存在");
            return "redirect:/sales";
        }
        
        SaleRecord sale = saleOpt.get();
        model.addAttribute("sale", sale);
        
        // 获取同一商品的所有销售记录
        List<SaleRecord> productSales = saleRecordService.findByProductId(sale.getProduct().getId());
        model.addAttribute("productSales", productSales);
        
        return "sale/detail";
    }
    
    @GetMapping("/product/{productId}")
    public String viewProductSales(@PathVariable Long productId, Model model, RedirectAttributes redirectAttributes) {
        Optional<Product> productOpt = productService.findById(productId);
        
        if (!productOpt.isPresent()) {
            redirectAttributes.addFlashAttribute("error", "商品不存在");
            return "redirect:/products";
        }
        
        model.addAttribute("product", productOpt.get());
        model.addAttribute("sales", saleRecordService.findByProductId(productId));
        return "sale/product-sales";
    }
    
    @GetMapping("/delete/{id}")
    public String deleteSale(@PathVariable Long id, RedirectAttributes redirectAttributes) {
        try {
            Optional<SaleRecord> saleOpt = saleRecordService.findById(id);
            
            if (!saleOpt.isPresent()) {
                redirectAttributes.addFlashAttribute("error", "销售记录不存在");
                return "redirect:/sales";
            }
            
            // 删除销售记录（同时会增加库存）
            saleRecordService.deleteSaleRecord(id);
            
            redirectAttributes.addFlashAttribute("success", "销售记录删除成功");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "销售记录删除失败: " + e.getMessage());
        }
        return "redirect:/sales";
    }
    
    @GetMapping("/top-selling")
    public String topSellingProducts(Model model, 
                                    @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
                                    @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
        
        LocalDateTime start = startDate != null ? startDate.atStartOfDay() : LocalDateTime.now().minusMonths(1);
        LocalDateTime end = endDate != null ? endDate.atTime(LocalTime.MAX) : LocalDateTime.now();
        
        List<Map<String, Object>> topProducts = saleRecordService.findTopSellingProducts(start, end, 10);
        model.addAttribute("topProducts", topProducts);
        model.addAttribute("startDate", startDate);
        model.addAttribute("endDate", endDate);
        
        return "sale/top-selling";
    }
    
    @GetMapping("/product-info/{productId}")
    @ResponseBody
    public Map<String, Object> getProductInfo(@PathVariable Long productId) {
        Map<String, Object> result = new HashMap<>();
        Optional<Product> productOpt = productService.findById(productId);
        
        if (productOpt.isPresent()) {
            Product product = productOpt.get();
            result.put("success", true);
            result.put("name", product.getName());
            result.put("category", product.getCategory());
            result.put("quantity", product.getQuantity());
            result.put("unit", product.getUnit());
            result.put("price", product.getSellingPrice());
            result.put("purchasePrice", product.getPurchasePrice());
        } else {
            result.put("success", false);
            result.put("message", "商品不存在");
        }
        
        return result;
    }
} 